package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Orders;
import com.example.entity.Product;
import com.example.generator.OrderNoGenerator;
import com.example.mapper.OrdersMapper;
import com.example.mapper.ProductMapper;
import com.example.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author yzy
 * @since 2025-08-04
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Integer placeOrder(Integer userId, Integer productId) {
        return null;
    }

    @Override
    public void addorder(Integer productId, Integer userId) {
        //获取商品
        Product product = productMapper.selectById(productId);
        //库存判断
        if (product.getInventory() > 0) {
            product.setInventory(product.getInventory()-1);
        }
        productMapper.updateById(product);
        Orders orders = new Orders();
        orders.setCode(OrderNoGenerator.generateOrderNo());
        orders.setProductId(productId);
        orders.setUserId(userId);
        orders.setBuyPrice(product.getPrice());
        orders.setTradeStatus(false);
        orders.setCreateTime(LocalDateTime.now());
        // 生成唯一订单号的核心逻辑（无锁实现）
        String orderCode = null;
        int maxRetry = 9999; // 无锁场景建议提高重试次数
        int retryCount = 0;
        // 循环生成并校验订单号，直到成功或达到最大重试次数
        while (retryCount < maxRetry) {
            // 1. 生成订单号（依赖生成规则的低冲突性）
            String tempCode = OrderNoGenerator.generateOrderNo();
            // 2. 查询订单号是否已存在
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", tempCode);
            Orders existOrder = ordersMapper.selectOne(queryWrapper);
            if (existOrder == null) {
                // 3. 订单号不存在，可使用
                orderCode = tempCode;
                break;
            }
            // 订单号已存在，重试
            retryCount++;
            try {
                // 无锁场景建议延长重试间隔，降低冲突概率
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("线程中断", e);
            }
        }
        // 检查是否成功生成唯一订单号
        if (orderCode == null) {
            throw new RuntimeException("生成订单号失败，请重试");
        }
        // 设置订单号并插入
        orders.setCode(orderCode);
        ordersMapper.insert(orders);

    }

    @Override
    public void completeOrder(Orders orders) {
        orders.setTradeStatus(true);
        orders.setTradeTime(LocalDateTime.now());
        ordersMapper.updateById(orders);
    }
}
